import 'package:dio/dio.dart';

class CartAPI {
  final Dio _dio;

  CartAPI(this._dio);

  // 添加购物车
  /// int productId   商品 id
  /// int cartNum     商品数量
  /// String uniqueId 多规格商品 sku 的唯一标识
  /// int new         购物车类型 | 0 加入购物车， 1 直接购买
  Future<dynamic> addToCart(int productId, int cartNum, [String uniqueId = '',
    int isNew = 0]) async {
    // 表单数据
    FormData formData = FormData.fromMap({
      "productId": productId,
      "cartNum": cartNum,
      "uniqueId": uniqueId,
      "new": isNew,
    });
    Response res = await _dio.post('/cart/add', data: formData);

    return res.data;
  }

  // 购物车列表
  Future<dynamic> list() async {
    Response res = await _dio.get('/cart/list');
    // print('购物车列表接口');
    return res.data;
  }
  
  /// 更新购物车中的商品数量
  /// type -1 直接修改，0 减少，1 增加
  Future<dynamic> setNum({
    required int productId, 
    int cartNum = 1, 
    String unique = '',
    int type = 0
  }) async {
    // 表单数据
    FormData formData = FormData.fromMap({
      "product_id": productId,
      "num": cartNum,
      "unique": unique,
      "type": type,
    });
    Response res = await _dio.post('/v2/set_cart_num', data: formData);

    return res.data;
  }

  /// 删除购物车
  /// 删除单个商品 ids = "1"
  /// 删除多个商品 ids = "1,2,3"
  Future<dynamic> deleteFromCart(String ids) async {
    // 表单数据
    FormData formData = FormData.fromMap({
      "ids": ids,
    });
    Response res = await _dio.post('/cart/del', data: formData);

    if (res.data != null) {
      return res.data['status'] == 200 ? true : false;
    } else {
      return false;
    }
  }
}